import { setTreeData } from '@/utils'
import { ColumnsTypes, ProTableParams } from '../types'

export const useProTable = (
  apiRequest: (params: any) => Promise<any>,
  dataKey: string,
  columns: ColumnsTypes[],
  rowKey: string,
  isTreeData: boolean
) => {
  const state = reactive<ProTableParams>({
    loading: false,
    // 查询表单项配置
    searchColumns: [],
    // 查询表单参数
    searchModel: {},
    // 表头控制显示隐藏的配置项
    settingColumns: [],
    // 表格表头配置项
    tableColumns: [],
    // 表格数据
    tableData: [],
    // 分页显示页数
    pageSizes: [10, 20, 50, 100, 200],
    // 分业参数
    pagination: {
      current: 1,
      size: 20,
      total: 0
    }
  })

  /**
   * 初始化查询参数
   * @param searchValue 查询表单的默认参数
   */
  const initSearch = () => {
    state.searchModel = {}
    state.searchColumns = []

    state.searchColumns.push(...columns.filter((item) => item.showInSearch))

    state.searchColumns.map((item) => {
      state.searchModel[item.prop!] = item.searchValue
    })
  }

  const initTable = () => {
    state.settingColumns = []

    state.settingColumns = columns.filter((item) => {
      if (!item.hideInTable) {
        item.showInTable = true
        return item
      }
    })
  }

  const watchTableColumns = () => {
    state.tableColumns = []

    state.tableColumns = state.settingColumns.filter((item) => item.showInTable)
  }

  /** 获取表格数据 */
  const fetchTableListData = async () => {
    try {
      const params = {
        ...state.searchModel,
        ...state.pagination
      }
      const res = await apiRequest(params)

      state.tableData = isTreeData
        ? setTreeData(res[dataKey], rowKey)
        : res[dataKey]
    } catch (err) {
      console.log(err)
    }
  }

  /**
   * 查询数据
   */
  const search = () => {
    state.pagination.current = 1
    fetchTableListData()
  }

  /**
   * 重置查询表单
   */
  const reset = () => {
    initSearch()
    search()
  }

  /**
   * 每页条数改变
   * @param val 每页显示的条数
   */
  const handleSizeChange = (val: number) => {
    state.pagination.current = 1
    state.pagination.size = val
    search()
  }

  /**
   * 切换页数
   * @param val 页数值
   */
  const handleCurrentChange = (val: number) => {
    state.pagination.current = val
    search()
  }

  return {
    ...toRefs(state),
    initSearch,
    initTable,
    fetchTableListData,
    search,
    reset,
    watchTableColumns,
    handleSizeChange,
    handleCurrentChange
  }
}
